package com.sky.controller;

import com.sky.config.CommonConfig;
import com.sky.util.ChmodUtil;
import com.sky.util.PathUtil;
import com.sky.vo.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

;

@RestController
@RequestMapping("/file/")
@Slf4j
@Api(tags = {"文件上传下载管理"})
public class FileController {

    @Autowired
    private CommonConfig properties;

    @PostMapping("upload")
    @ApiOperation(value = "文件/图片上传")
    public AjaxResult handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("文件不能为空");
        }
        try {

            String fileName = file.getOriginalFilename();//原文件名称
            String uniqueName = UUID.randomUUID() + fileName;
//            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));//源文件后缀


            // 设置保存路径，这里假设保存在项目根目录下的uploads文件夹
            File destFile = new File(Paths.get(properties.getUploadDir(), uniqueName).toAbsolutePath().normalize().toString());
            // 确保目录路径存在
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            // 保存文件
            file.transferTo(destFile);
            ChmodUtil.chmodPath(properties.getUploadDir());
            return AjaxResult.success(PathUtil.getPath(properties.getUploadDir(),uniqueName));
        } catch (Exception e) {
            log.error("handleFileUpload 接口异常:" + e.getMessage(), e);
            return AjaxResult.error("文件上传失败"+e.getMessage());
        }
    }

    @GetMapping("download")
    @ApiOperation(value = "文件/图片下载")
    public void downloadResult(@RequestParam("path") String path, HttpServletResponse response) {

        try (InputStream is = Files.newInputStream(Paths.get(path))) {
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8"));
            IOUtils.copy(is, response.getOutputStream());
        }  catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
